package com.link.base.base.dept.controller;

import com.link.base.base.dept.model.Department;
import com.link.base.base.dept.model.DepartmentRelation;
import com.link.base.base.dept.service.DepartmentService;
import com.link.base.base.orgnization.model.Orgnization;
import com.link.base.core.apiutils.ApiBeanUtils;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.query.Sorter;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.ServiceException;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.util.StringUtils;
import com.link.core.cllog.LCLogger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author  unknwon
 * @date:   2018/11/9 16:08
 * @version 1.0
 */

@Controller
@RequestMapping("/link/dept")
public class DepartmentController extends BasicController<Department> {

    @Resource
    private DepartmentService departmentService;

    @Resource
    private KeyGenerateService keyGenerateService;

    @Override
    public BasicService<Department> getBasicService() throws Exception {
        return departmentService;
    }

    /**
     * 加载树
     */
    @RequestMapping(value = "/treelist", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> treelist(@JsonParam QueryParams qps, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            Department root = departmentService.queryRoot(new Department());
            departmentService.queryTreeByRoot(root);
            result.put("success", true);
            result.put("tree", true);
            //传根节点
            result.put("list", root);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("list", new Department());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 加载结构框图树
     */
    @RequestMapping(value = "/treelist/{initDeptId}")
    @ResponseBody
    public Department treelist(@PathVariable Long initDeptId,@JsonParam QueryParams qps, HttpSession session,
                               HttpServletRequest request, HttpServletResponse response) {
        Department root = new Department();
        try {
            root.setId(initDeptId);
            root = departmentService.queryById(root);
            departmentService.queryTreeByRoot1(root);
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return root;
    }

    /**
     * 选择父对象时的picklist
     */
    @RequestMapping(value = "/parentPicklist", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> parentPicklist(@JsonParam Department entity,@JsonParam QueryParams qps, HttpSession session,
                                              HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            //按创建时间来排序
            qps.addSorter(new Sorter("created", Sorter.DIR_DESC));
            String flag = "Y";
            if (StringUtils.equals(qps.getAttr1(), flag)) {
                //如果是组织
                qps.addFilter(new Filter("isOrg", qps.getAttr1()));
            }
            Department t = (Department) BasicModel.transformClass(Department.class, qps);
            //设置安全性
            t.preDealSecurity(request);
            List<Department> list = departmentService.queryDepartmentListRemoveIdAndChildrenPage(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(((BasicModel) t), list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Department>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 通用picklist
     */
    @RequestMapping(value = "/picklist", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> picklist(@JsonParam QueryParams qps, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            Department t = (Department) BasicModel.transformClass(Department.class, qps);
            //设置安全性
            t.preDealSecurity(request);
            List<Department> list = departmentService.queryByExamplePage(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(((BasicModel) t), list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Department>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 根据ID删除该记录以及其子对象
     */
    @RequestMapping(value = "/deleteWithChildById")
    @ResponseBody
    public Map<String, Object> deleteWithChildById(@JsonParam Department entity, HttpSession session,
                                                   HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("deleteWithChildById")
                .withMessage("根据ID删除该记录以及其子对象信息...").flush();
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            beforDelete(entity, request);
            checkData(entity, request);
            String base = "base";
            if (!checkExistDataCache(base, session, entity)) {
                throw new ServiceException("PUBLIC-031");
            }
            //审计追踪新建记录
            departmentService.deleteWithChildById(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }

        return result;
    }
    /**
     * <p>新建或更新部门信息</p>
     * @author yrf
     * @param model
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = "upsert", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> upsert(@RequestBody Department model,
                                      HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(4);

        try {
            Department dept = departmentService.getDept(model);
            Department parentDept = departmentService.getParentDept(model);
            if (dept == null) {
                dept = new Department();
                Long id = keyGenerateService.keyGenerate();
                dept.setRow_status("NEW");
                dept.setId(id);
            } else {
                dept.setRow_status("UPDATE");
            }
            Orgnization org = departmentService.getOrg(model);
            ApiBeanUtils.copyProperties(model, dept);
            dept.setParentDeptId(parentDept.getId());
            dept.setOrgId(org == null ? dept.getId() : org.getId());
            dept.setSource("SIEBEL");
            departmentService.upsert(dept);
            result.put("crmId", dept.getId());
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }


    @Override
    public void beforUpsert(Department entity, HttpServletRequest request) {
        entity.setIsOrg("N");
    }

    /**
     * 获取多层级部门关联关系
     * @author 姚江漪
     * @date 2019/04/02 23:20
     * @param departmentRelation
     */
    @RequestMapping(value = "/queryAreaRegionPage")
    @ResponseBody
    public Map<String, Object> queryAreaRegionPage(DepartmentRelation departmentRelation, QueryParams qps, HttpSession session,
                                                   HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            //设置安全性
            qps.preDealSecurity(request);
            DepartmentRelation t = (DepartmentRelation) BasicModel.transformClass(DepartmentRelation.class, qps);
            t.setDeptType(departmentRelation.getDeptType());
            t.setDeptType2(departmentRelation.getDeptType2());
            t.setDeptType3(departmentRelation.getDeptType3());
            t.setDeptType4(departmentRelation.getDeptType4());
            List<DepartmentRelation> departmentRelationList = departmentService.queryAreaRegionPage(t);
            result.put("success", true);
            result.put("rows", departmentRelationList);
            result.put("total",getCount(((BasicModel) t), departmentRelationList.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 提供app根据部门获取战区、片区、大区信息
     * @author 姚江漪
     * @date 2019/04/17 17:32
     */
    @RequestMapping(value = "/queryAPPUserAreaRegion")
    @ResponseBody
    public Map<String, Object> queryAPPUserAreaRegion(@RequestBody Department entity, QueryParams qps, HttpSession session,
                                                      HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Map<String, Object> areaRegionTier = departmentService.queryAPPUserAreaRegion(entity);
            result.put("success", true);
            result.put("result", areaRegionTier);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
